package com.example.wm.controller;

import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import com.example.wm.service.impls.OCRService;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/ocrs")
public class UploadimgController {
    @Value("${upload.path}")
    private String uploadPath;
    @Autowired
    private OCRService ocrService;

    @PostMapping("/extract-text2")
    public ResponseEntity<String> extractTextFromImage2(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("未选择图片!", HttpStatus.BAD_REQUEST);
        }

        try {
            // 从 MultipartFile 中读取图像数据
            InputStream inputStream = file.getInputStream();
            BufferedImage image = ImageIO.read(inputStream);

            // 检查图像是否有效
            if (image == null) {
                return new ResponseEntity<>("不支持的图像格式!", HttpStatus.BAD_REQUEST);
            }

            // 调用 OCR 服务
            String result = ocrService.extractTextFromImage((File) file);
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("文件读取错误: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("未知错误: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/saveFile")
    public Result saveFile(MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return ResultData.error(304, "文件为空,请选择一张图片上传");
        }

        // 确保上传目录存在
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                return ResultData.error(500, "上传目录创建失败");
            }
        }

        // 获取文件扩展名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return ResultData.error(304, "文件名无效");
        }
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 使用时间戳生成新的文件名
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String newFilename = timestamp + fileExtension;

        // 构建文件保存路径
        Path filePath = Paths.get(uploadPath, newFilename);

        // 保存文件到本地
        try (FileOutputStream fos = new FileOutputStream(filePath.toFile())) {
            fos.write(file.getBytes());
        } catch (IOException e) {
            return ResultData.error(500, "文件上传失败,请稍后再试");
        }

        // 构建返回的URL
        String fileUrl = "" + filePath.getFileName();

        // 返回成功结果
        return ResultData.success(fileUrl);
    }

    @PostMapping("/deleteimg")
    private Result deleteimg(@RequestBody List<String> list) throws MalformedURLException {
        boolean allDeleted = true;
        StringBuilder errorMessages = new StringBuilder();
        for (String s : list) {
            // URL url = new URL(s);
            // String fileName = url.getFile().substring(url.getFile().lastIndexOf('/') +
            // 1);
            // System.out.println( fileName+"fileName" );
            File file = new File(uploadPath, s);

            if (file.exists()) {
                if (!file.delete()) {
                    allDeleted = false;
                    errorMessages.append("文件 ").append(s).append(" 删除失败; ");
                }
            } else {
                allDeleted = false;
                errorMessages.append("文件 ").append(s).append(" 不存在; ");
            }
        }

        if (allDeleted) {
            return ResultData.success("所有文件删除成功");
        } else {
            return ResultData.error(304, errorMessages.toString());
        }
    }

    @PostMapping("/deleteimg2")
    public Result deleteImages2(@RequestBody List<String> list) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<List<String>> request = new HttpEntity<>(list, headers);
        RestTemplate restTemplate = new RestTemplate();

        // 发送 POST 请求
        String response = restTemplate.postForObject("http://118.31.75.80:8050/ours/deleteimg", request, String.class);

        // 处理响应
        if (response != null) {
            System.out.println("服务器响应: " + response);
            return ResultData.success(response);
        } else {
            System.out.println("没有收到服务器响应");
            return ResultData.error(304, "删除失败");
        }
    }

    @GetMapping("/{filename}")
    public ResponseEntity<byte[]> getImage(@PathVariable String filename) {
        try {
            // 构建文件路径
            File file = new File(uploadPath, filename);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }

            // 读取文件内容
            byte[] imageContent = new byte[(int) file.length()];
            try (FileInputStream fis = new FileInputStream(file)) {
                fis.read(imageContent);
            }

            // 返回文件内容
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_JPEG) // 根据文件类型设置 MIME 类型
                    .body(imageContent);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    public String togbk(String args) {
        String originalString = args;

        try {
            // 将字符串编码为 GBK
            byte[] gbkBytes = originalString.getBytes(StandardCharsets.ISO_8859_1);
            // 可以将字节数组转换回字符串进行显示,注意这只是为了展示效果
            String convertedString = new String(gbkBytes, "GBK");
            System.out.println("Original String: " + originalString);
            System.out.println("GBK Encoded Bytes: " + java.util.Arrays.toString(gbkBytes));
            System.out.println("Converted Back String: " + convertedString);
            return convertedString;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private File convertMultiPartToFile(MultipartFile file) throws IOException {
        File convFile = new File(System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename());
        file.transferTo(convFile);
        return convFile;
    }

}
